package com.study.filter;

import com.study.constant.CommonConstant;
import com.study.util.TokenParseUtil;
import com.study.vo.LoginUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户身份统一登录拦截
 */

@Slf4j
@Component
@SuppressWarnings("all")
public class LoginUserInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        //验证白名单
        if(checkWhiteListUrl(request.getRequestURI())){
            return true;
        }

        //从http header 里面拿到token
        String token = request.getHeader(CommonConstant.JWT_USER_INFO_KEY);

        LoginUserInfo loginUserInfo = null;

        try {
            loginUserInfo = TokenParseUtil.parseUserInfoFromToken(token);
        } catch (Exception e) {
            log.error("parse login user info error: [{}]",e.getMessage(),e);
        }

        if(null == loginUserInfo){
            throw new RuntimeException("不能解析当前登录用户");
        }

        //设置当前请求上下文、把用户信息填充进去
        AccessContext.setLoginUserInfo(loginUserInfo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //在请求完全结束后调用、常用于清理资源等工作
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        if(null != AccessContext.getLoginUserInfo()){
            AccessContext.clearLoginUserInfo();
        }
    }

    /**
     * 校验是否是白名单
     * @param url
     * @return
     */
    private boolean checkWhiteListUrl(String url){

        return org.apache.commons.lang3.StringUtils.containsAny(
                url,
                "springfox","swagger","swagger-ui.html",
                "v2","webjars","doc.html"
        );
    }
}
